<template>
  <div class="workshop-container">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete" :disabled="selectedRows.length === 0">批量删除</el-button>
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="code" label="编号" width="120">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.code"
            size="small"
            placeholder="请输入编号"
          />
          <span v-else>{{ scope.row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" width="180">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.name"
            size="small"
            placeholder="请输入名称"
          />
          <span v-else>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="location" label="位置" width="180">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.location"
            size="small"
            placeholder="请输入位置"
          />
          <span v-else>{{ scope.row.location }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager" label="负责人" width="120">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.manager"
            size="small"
            placeholder="请输入负责人"
          />
          <span v-else>{{ scope.row.manager }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-select
            v-if="scope.row.isEdit"
            v-model="scope.row.status"
            size="small"
            placeholder="请选择状态"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-tag :type="scope.row.status === '启用' ? 'success' : 'danger'" v-else>
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述">
        <template #default="scope">
          <el-input
            v-if="scope.row.isEdit"
            v-model="scope.row.description"
            size="small"
            placeholder="请输入描述"
            type="textarea"
          />
          <span v-else>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="creator" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div v-if="scope.row.isEdit">
            <el-button type="primary" link @click="handleSave(scope.row)">保存</el-button>
            <el-button type="danger" link @click="handleCancel(scope.row)">取消</el-button>
          </div>
          <div v-else>
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增车间' : '编辑车间'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="编号" prop="code">
          <el-input v-model="formData.code" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-input v-model="formData.location" placeholder="请输入位置" />
        </el-form-item>
        <el-form-item label="负责人" prop="manager">
          <el-input v-model="formData.manager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add or edit
const formRef = ref(null)
const formData = reactive({
  id: '',
  code: '',
  name: '',
  location: '',
  manager: '',
  status: '启用',
  description: ''
})

// 表单验证规则
const rules = {
  code: [{ required: true, message: '请输入编号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  location: [{ required: true, message: '请输入位置', trigger: 'blur' }],
  manager: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 状态选项
const statusOptions = ref([
  { value: '启用', label: '启用' },
  { value: '停用', label: '停用' }
])

// 初始化数据
onMounted(() => {
  fetchData()
})

// 获取数据
const fetchData = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    // 生成当前一星期内的日期
    const generateRecentDates = (index) => {
      const now = new Date()
      // 创建时间：当前日期往前推 (index % 5 + 2) 天
      const createDate = new Date(now)
      createDate.setDate(now.getDate() - (index % 5 + 2))
      const createTime = createDate.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
      
      // 更新时间：创建时间往后推2天
      const updateDate = new Date(createDate)
      updateDate.setDate(createDate.getDate() + 2)
      const updateTime = updateDate.toLocaleString('zh-CN', { 
        year: 'numeric', 
        month: '2-digit', 
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
      
      return { createTime, updateTime }
    }

    const mockData = [
      {
        id: 1,
        code: 'WS001',
        name: '灌装车间',
        location: '北京海淀区',
        manager: '张三',
        status: '启用',
        description: '主要负责产品灌装工作，共有3条生产线',
        creator: '(test)AAA',
        ...generateRecentDates(1)
      },
      {
        id: 2,
        code: 'WS002',
        name: '包装车间',
        location: '北京朝阳区',
        manager: '李四',
        status: '启用',
        description: '负责产品包装工作，共有2条包装线',
        creator: '(test)AAA',
        ...generateRecentDates(2)
      },
      {
        id: 3,
        code: 'WS003',
        name: '原料车间',
        location: '北京丰台区',
        manager: '王五',
        status: '启用',
        description: '负责原料处理和加工',
        creator: '(test)AAA',
        ...generateRecentDates(3)
      },
      {
        id: 4,
        code: 'WS004',
        name: '质检车间',
        location: '北京海淀区',
        manager: '赵六',
        status: '启用',
        description: '负责产品质量检测',
        creator: '(test)AAA',
        ...generateRecentDates(4)
      },
      {
        id: 5,
        code: 'WS005',
        name: '仓储车间',
        location: '北京大兴区',
        manager: '钱七',
        status: '停用',
        description: '负责产品仓储和物流',
        creator: '(test)AAA',
        ...generateRecentDates(5)
      }
    ]
    
    // 添加更多模拟数据
    const additionalData = [
      {
        id: 6,
        code: 'WS006',
        name: '研发车间',
        location: '北京海淀区',
        manager: '孙八',
        status: '启用',
        description: '负责新产品研发和测试',
        creator: '(test)AAA',
        ...generateRecentDates(6)
      },
      {
        id: 7,
        code: 'WS007',
        name: '维修车间',
        location: '北京朝阳区',
        manager: '周九',
        status: '启用',
        description: '负责设备维修和保养',
        creator: '(test)AAA',
        ...generateRecentDates(7)
      },
      {
        id: 8,
        code: 'WS008',
        name: '组装车间',
        location: '北京顺义区',
        manager: '吴十',
        status: '停用',
        description: '负责产品组装',
        creator: '(test)AAA',
        ...generateRecentDates(8)
      }
    ]
    
    mockData.push(...additionalData)
    
    tableData.value = mockData.map(item => ({
      ...item,
      isEdit: false,
      _originalData: { ...item } // 保存原始数据，用于取消编辑
    }))
    
    total.value = mockData.length
    loading.value = false
  }, 500)
}

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 新增按钮
const handleAdd = () => {
  dialogType.value = 'add'
  formData.id = ''
  formData.code = ''
  formData.name = ''
  formData.location = ''
  formData.manager = ''
  formData.status = '启用'
  formData.description = ''
  dialogVisible.value = true
  // 在下一个事件循环中重置表单验证
  setTimeout(() => {
    formRef.value?.resetFields()
  })
}

// 编辑按钮
const handleEdit = (row) => {
  row.isEdit = true
  // 保存原始数据，用于取消编辑
  row._originalData = { ...row }
}

// 保存行内编辑
const handleSave = (row) => {
  // 这里应该调用API保存数据
  ElMessage.success('保存成功')
  row.isEdit = false
  row.updateTime = new Date().toLocaleString()
}

// 取消行内编辑
const handleCancel = (row) => {
  // 恢复原始数据
  Object.keys(row._originalData).forEach(key => {
    if (key !== '_originalData' && key !== 'isEdit') {
      row[key] = row._originalData[key]
    }
  })
  row.isEdit = false
}

// 删除单行
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API删除数据
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index !== -1) {
      tableData.value.splice(index, 1)
      total.value--
      ElMessage.success('删除成功')
    }
  }).catch(() => {})
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }
  
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API批量删除数据
    const ids = selectedRows.value.map(row => row.id)
    tableData.value = tableData.value.filter(item => !ids.includes(item.id))
    total.value -= selectedRows.value.length
    selectedRows.value = []
    ElMessage.success('批量删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (dialogType.value === 'add') {
        // 新增
        const newId = Math.max(...tableData.value.map(item => item.id)) + 1
        const newRow = {
          id: newId,
          code: formData.code,
          name: formData.name,
          location: formData.location,
          manager: formData.manager,
          status: formData.status,
          description: formData.description,
          creator: '(test)AAA',
          createTime: new Date().toLocaleString(),
          updateTime: '',
          isEdit: false
        }
        tableData.value.push(newRow)
        total.value++
        ElMessage.success('添加成功')
      } else {
        // 编辑
        const index = tableData.value.findIndex(item => item.id === formData.id)
        if (index !== -1) {
          tableData.value[index] = {
            ...tableData.value[index],
            code: formData.code,
            name: formData.name,
            location: formData.location,
            manager: formData.manager,
            status: formData.status,
            description: formData.description,
            updateTime: new Date().toLocaleString()
          }
          ElMessage.success('编辑成功')
        }
      }
      dialogVisible.value = false
    } else {
      return false
    }
  })
}
</script>

<style scoped>
.workshop-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-start;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table :deep(.el-table__row) {
  height: 50px;
}
</style>
